<?php

class Lib_Repair_Base_Code
{
    const CODE_EXPIRE = 600; //验证码失效时间
    const SECURITY = 3;
    private static $mem_key_pre = '__MobileVerify_KEY_';


    /**
     * 生成验证码
     */
    public static function getCode($length = 6, $numeric = 0)
    {
        PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
        if ($numeric) {
            $hash = sprintf('%0' . $length . 'd', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash = '';
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for ($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    }

    /**
     * 保存验证码
     * @param $mobile
     * @param $code
     * @param $scene
     */
    public static function saveCode($mobile, $code, $app, $scene)
    {
        $memKey = self::getMemKey($app,$scene,$mobile);
        LrFunc_Cachefunc::getInstance()->set($memKey, $code, self::CODE_EXPIRE);
    }

    /**
     * 校验验证码
     * @param $mobile
     * @param $code
     * @param $scene
     * @return bool
     */
    public static function verifyCode($mobile, $code,$app, $scene)
    {
        $memKey = self::getMemKey($app,$scene,$mobile);
        $exist_code = LrFunc_Cachefunc::getInstance()->get($memKey);
        if (empty($exist_code)) {
            return false;
        }
        if (!$exist_code || $exist_code != $code) {
            return false;
        }
        //验证通过后失效
        LrFunc_Cachefunc::getInstance()->delete($memKey);
        return true;
    }

    public static function getMemKey($app, $scene, $mobile)
    {
        return self::$mem_key_pre . $app . '_' . $scene . '_' . $mobile;
    }

    //发送短信验证图形验证码（现 提现和修改手机号在使用）
    public static function checkGraphicVerificationCode($mobile, $scene,$key, $code)
    {
        $is_send = LrFunc_Redisfunc::getInstance()->checkceiling('tianyan_sms_'.$scene, $mobile, 10, 'get');
        if ($is_send > self::SECURITY) {
            if (!$key or !$code) {
                $obj = new Lib_Vcode();
                $obj->setCodeText();
                $obj->createImg();
                return array('code' => 4569, 'message' => '需要验证码', 'data' => $obj->outputBase64($mobile));
            }
            $userCode = $code;
            if (md5($userCode . $mobile) != $key) {
                return array('code' => 4105, 'message' => '图片验证码错误');
            }
            $code = LrFunc_Cachefunc::getInstance()->get($key);
            if ($userCode != $code) {
                return array('code' => 4105, 'message' => '图片验证码错误');
            }
            LrFunc_Cachefunc::getInstance()->delete($key);

        }
        LrFunc_Redisfunc::getInstance()->checkceiling('tianyan_sms_'.$scene, $mobile, 10);
        return true;
    }

}